package com.shjn.squirrel.utils;

import android.content.Intent;
import android.util.Log;

import com.shjn.squirrel.application.MyApplication;
import com.shjn.squirrel.model.LocalStorage;
import com.shjn.squirrel.service.AppCrashService;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 捕捉APP崩溃信息工具类
 */
public class AppCrashUtils {

    private static Thread.UncaughtExceptionHandler defaultHandler = Thread.getDefaultUncaughtExceptionHandler();

    private AppCrashUtils() {
    }

    /**
     * 开启App崩溃监听
     */
    public static void startListener() {
        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread thread, Throwable throwable) {
                appCrashInfo(thread, throwable);
            }
        });
    }

    /**
     * 捕捉App崩溃信息
     *
     * @param thread
     * @param throwable
     */
    private static void appCrashInfo(final Thread thread, final Throwable throwable) {
        //获取崩溃时的UNIX时间戳
        long timeMillis = System.currentTimeMillis();
        //将时间戳转换成人类能看懂的格式，建立一个String拼接器
        StringBuilder stringBuilder = new StringBuilder(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date(timeMillis)));
        stringBuilder.append(":\n");
        //获取错误信息
        stringBuilder.append(throwable.getMessage());
        stringBuilder.append("\n");
        //获取堆栈信息
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        throwable.printStackTrace(pw);
        stringBuilder.append(sw.toString());
        //完整的错误信息
        String errorLog = stringBuilder.toString();
        Log.i("info", "uncaughtException: " + errorLog);
        //开启另一个进程服务，上传错误信息到服务器
        Intent intent = new Intent(MyApplication.getInstance(), AppCrashService.class);
        intent.putExtra("deviceID", LocalStorage.getDeviceID(MyApplication.getInstance()));
        intent.putExtra("errorLog", errorLog);
        MyApplication.getInstance().startService(intent);
        //最后如何处理这个崩溃，这里使用默认的处理方式让APP停止运行
        defaultHandler.uncaughtException(thread, throwable);
    }

}
